package LeetCode.leetcode63;

class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int m = obstacleGrid.length;
        int n = obstacleGrid[0].length;
        int[][] dp = new int[m][n];
        if (obstacleGrid[0][0] == 0){
            dp[0][0] = 1;
        }else {
            dp[0][0] = 0;
        }
        for (int i = 1; i < m; i++) {
            if (dp[i-1][0] == 1) {
                if (obstacleGrid[i][0] == 0) {
                    dp[i][0] = 1;
                } else {
                    dp[i][0] = 0;
                }
            }else{
                dp[i][0] = 0;
            }
        }
        for (int i = 1; i < n; i++) {
            if (dp[0][i-1] == 1) {
                if (obstacleGrid[0][i] == 0) {
                    dp[0][i] = 1;
                } else {
                    dp[0][i] = 0;
                }
            }else {
                dp[0][i] = 0;
            }
        }
        for (int i = 1; i < n; i++) {
            for (int j = 1; j < m; j++) {
                if (obstacleGrid[j][i] != 1) {
                    if (obstacleGrid[j][i-1] == 1 && obstacleGrid[j-1][i] == 0){
                        dp[j][i] = dp[j - 1][i];
                    }else if (obstacleGrid[j-1][i] == 1 && obstacleGrid[j][i-1] == 0){
                        dp[j][i] = dp[j][i - 1];
                    }else if (obstacleGrid[j-1][i] == 0 && obstacleGrid[j][i-1] == 0){
                        dp[j][i] = dp[j - 1][i] + dp[j][i - 1];
                    }else {
                        dp[j][i] = 0;
                    }
                }
            }
        }
        return dp[m-1][n-1];
    }
}